import "reflect-metadata";
import { createConnection } from "typeorm";
import { OnlineStatistics } from "../entity/OnlineStatistics";
import { Request, Response } from "express";

let moment = require('moment-timezone');

const connR = createConnection("role");

export function onlineRoute(app: any) {

    app.get('/api/online/day/:start_time', function (req: Request, res: Response) {

        let start_time = moment(req.params.start_time).format("YYYY-MM-DD");
        let end_time = start_time + " 23:59:59";

        connR.then(async connection => {

            let data = await connection.getRepository(OnlineStatistics).createQueryBuilder()
                .select("max(num)", "num")
                .addSelect("to_char(created_at, 'HH24')", "created_at")
                .where("created_at >= :start_time and created_at <= :end_time", { start_time: start_time, end_time: end_time })
                .groupBy("to_char(created_at, 'HH24')")
                .orderBy("created_at").getRawMany();

            res.send(data)

        }).catch(error => console.log(error));
    })

    app.get('/api/online/month/:start_time', function (req: Request, res: Response) {

        let start_time = moment(req.params.start_time).format("YYYY-MM-DD");
        let end_time = moment(req.params.start_time).add(1, "month").add(-1, "day").format("YYYY-MM-DD");

        connR.then(async connection => {

            let data = await connection.getRepository(OnlineStatistics).createQueryBuilder()
                .select("max(num)", "num")
                .addSelect("to_char(created_at, 'YYYY-MM-DD')", "created_at")
                .where("created_at >= :start_time and created_at <= :end_time", { start_time: start_time, end_time: end_time })
                .groupBy("to_char(created_at, 'YYYY-MM-DD')")
                .orderBy("created_at").getRawMany();

            res.send(data)

        }).catch(error => console.log(error));
    })

    app.get('/online/day', function (req: Request, res: Response) {

        connR.then(async connection => {

            let data = await connection.getRepository(OnlineStatistics).findOne({ order: { id: 'DESC' } });

            res.render('online/day', { date: moment().format("YYYY-MM-DD"), last: data });

        }).catch(error => console.log(error));
    })

    app.get('/online/month', function (req: Request, res: Response) {

        res.render('online/month', { month: moment().format("YYYY-MM") })
    })
}
